package com.it.base.core.system.dict.service.impl;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.base.common.view.PageResult;
import com.it.base.core.system.dict.mapper.SysDictTypeMapper;
import com.it.base.core.system.dict.model.entity.SysDictType;
import com.it.base.core.system.dict.model.from.SysDictTypeSelectPageListFormDTO;
import com.it.base.core.system.dict.model.from.SysDictTypeValidatorFormDTO;
import com.it.base.core.system.dict.service.ISysDictTypeService;
import com.it.base.support.string.StringUtil;

@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

	@Autowired
	private SysDictTypeMapper dictMapper;

	@Override
	public PageResult<SysDictType> selectPageList(SysDictTypeSelectPageListFormDTO sysDictTypeListFormDTO) {
		QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();

		if (StringUtil.isNotBlank(sysDictTypeListFormDTO.getName())) {
			queryWrapper.lambda().like(SysDictType::getName, sysDictTypeListFormDTO.getName());
		}

		if (StringUtil.isNotBlank(sysDictTypeListFormDTO.getType())) {
			queryWrapper.lambda().likeRight(SysDictType::getType, sysDictTypeListFormDTO.getType());
		}

		if (sysDictTypeListFormDTO.getStatus() != null) {
			queryWrapper.lambda().eq(SysDictType::getStatus, sysDictTypeListFormDTO.getStatus());
		}

		if (sysDictTypeListFormDTO.getBeginTime() != null) {
			queryWrapper.lambda().ge(SysDictType::getCreateTime, sysDictTypeListFormDTO.getBeginTime());
		}

		if (sysDictTypeListFormDTO.getEndTime() != null) {
			queryWrapper.lambda().ge(SysDictType::getCreateTime, sysDictTypeListFormDTO.getEndTime());
		}
		queryWrapper.lambda().orderByDesc(SysDictType::getCreateTime);
		IPage<SysDictType> page = dictMapper.selectPage(
				new Page<>(sysDictTypeListFormDTO.getPageNo(), sysDictTypeListFormDTO.getPageSize()), queryWrapper);
		return new PageResult<>(page.getTotal(), page.getRecords());
	}

	@Override
	public boolean validatorExist(@Valid SysDictTypeValidatorFormDTO sysDictTypeValidatorFormDTO) {
		QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysDictType::getType, sysDictTypeValidatorFormDTO.getType());
		if (StringUtil.isNotBlank(sysDictTypeValidatorFormDTO.getId())) {
			queryWrapper.lambda().ne(SysDictType::getId, sysDictTypeValidatorFormDTO.getId());
		}
		return this.count(queryWrapper) > 0;
	}

	@Override
	public SysDictType selectOne(String id) {
		return this.getById(id);
	}

}
